import SettingMsg from "./msgType/SettingMsg";
import { MessageBox } from "element-ui";
import { fetchConfig } from "@/api/common";
export default class IM {
    constructor() {
        this.globalListener = null;
        this.chatListener = null;
        this.taskChatListener = null;
        this.listenerTaskId = null;
    }

    init(userId) {
        return new Promise(resolve => {
            fetchConfig().then(config => {
                console.log(config, "wsconfig");
                this.url = config.ws;
                this.userId = userId;
                this.openWebsocket();
                resolve(true);
            });
        });
    }

    openWebsocket() {
        console.log("websocket:", "初始化连接", "连接地址：", this.url + this.userId);
        this.ws = new WebSocket(this.url + this.userId);
    }

    joinChat(chatId, userName, customerId, customerName) {
        console.log(chatId, userName, customerId, customerName);
        this.chatId = chatId;
        this.userName = userName;
        this.customerId = customerId;
        this.customerName = customerName;
    }

    open() {
        this.ws.onopen = event => {
            // 建立连接
            console.log("websocket:", "已建立连接");
            this.sendHeartbeat();
            this.setPlatform();
            this.ws.onmessage = event => {
                let msgBody = JSON.parse(event.data);
                if (this.listenerTaskId != null && this.taskChatListener != null) {
                    let taskInfo = JSON.parse(msgBody.body);
                    if (taskInfo.taskId == this.listenerTaskId) {
                        this.taskChatListener(msgBody);
                    } else {
                        this.globalListener(msgBody);
                    }
                } else {
                    this.globalListener(msgBody);
                }
            };
        };
        this.ws.onclose = event => {
            MessageBox.confirm("当前账号与服务器连接中断，请重新连接", "连接失败", {
                confirmButtonText: "重新连接",
                type: "warning",
                showClose: false,
                showCancelButton: false,
                closeOnClickModal: false,
                beforeClose: (action, instance, done) => {
                    if (action == "confirm") {
                        this.openWebsocket();
                        this.open();
                    }
                    done();
                },
            });
        };
    }

    sendHeartbeat() {
        setInterval(() => {
            this.ws.send(
                JSON.stringify({
                    type: "heartbeat",
                    body: JSON.stringify({}),
                })
            );
        }, 5000);
    }

    setGlobalListener(listener) {
        console.log("websocket:", "开启全局监听");
        this.globalListener = listener;
    }

    setChatListener(listener) {
        console.log("websocket:", "切换到单聊监听");
        this.chatListener = listener;
    }

    setTaskListener(taskId, listener) {
        console.log("websocket:", "切换到任务监听，任务ID:" + taskId);
        this.listenerTaskId = taskId;
        this.taskChatListener = listener;
    }

    clearChatListener() {
        console.log("websocket:", "切换到全局监听");
        this.chatListener = null;
    }

    clearTaskChatListener() {
        this.listenerTaskId = null;
        this.taskChatListener = null;
    }

    setPlatform() {
        let msg = new SettingMsg();
        msg.setPlatform("web");
        this.ws.send(this.makeMessagePackage(msg, "setting"));
    }

    sendMsg(msg, type) {
        msg.setChatId(this.chatId);
        msg.setUserId(this.userId);
        msg.setUserName(this.userName);
        msg.setCustomerId(this.customerId);
        msg.setCustomerName(this.customerName);
        this.ws.send(this.makeMessagePackage(msg, type));
    }

    sendTaskMsg(msg, type) {
        try {
            this.ws.send(this.makeMessagePackage(msg, type));
        } catch (e) {
            console.log(e);
        }
    }

    makeMessagePackage(msg, type) {
        return JSON.stringify({
            type: type,
            body: JSON.stringify(msg),
        });
    }
}
